package priv.happy.mealpickpro.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import priv.happy.mealpickpro.domain.Tag;
import priv.happy.mealpickpro.emum.SystemStatusCode;
import priv.happy.mealpickpro.service.TagService;
import priv.happy.mealpickpro.vo.ApiResponse;

import java.time.Duration;
import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: MealPick
 * @Package_name: priv.happy.mealpick.controller
 * @Date: 2023/7/2 19:09
 * @Description:
 */
@RestController
@RequestMapping("/api/v2/tag")
public class TagController {

    @Autowired
    TagService tagService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 根据名称查询某个用户的标签
     *
     * @param tagName 要查询的标签名称
     * @param userId  当前用户的id
     * @return 返回查询的结果
     */
    @GetMapping("/getOne")
    public ApiResponse<List<Tag>> doGetTagByName(String tagName, Integer userId) {
        ApiResponse<List<Tag>> listApiResponse = new ApiResponse<>();
        try {
            listApiResponse.setData(tagService.list(new QueryWrapper<Tag>()
                            .like("name", tagName)
                            .eq("post_user_id", userId)))
                    .setCode(200).setMessage("查询成功").setSuccess(true);
        } catch (Exception e) {
            listApiResponse.setCode(500).setMessage("拉取标签信息失败").setSuccess(false);
        }
        return listApiResponse;
    }

    /**
     * 查询所有标签信息
     *
     * @return 返回查询的结果集
     */
    @GetMapping("/{userId}")
    public ApiResponse<List<Tag>> doGetAllTags(@PathVariable Integer userId) {
        ApiResponse<List<Tag>> listApiResponse = new ApiResponse<>();
        try {
            if (userId != null && userId > 0) {
                listApiResponse.setData(tagService.getAllTags(userId)).setCode(SystemStatusCode.SUCCESS.getCode()).setMessage("查询成功").setSuccess(true);
            } else {
                listApiResponse.setCode(SystemStatusCode.BAD_REQUEST.getCode()).setMessage("拉取标签信息失败").setSuccess(false);
            }
        } catch (Exception e) {
            listApiResponse.setCode(SystemStatusCode.INTERNAL_SERVER_ERROR.getCode()).setMessage("拉取标签信息失败").setSuccess(false);
        }
        return listApiResponse;
    }

    /**
     * 新增标签
     *
     * @param tag 新增的标签信息
     * @return 返回成功与否
     */
    @PostMapping()
    public ApiResponse<String> doAddTag(@RequestBody Tag tag) {
        ApiResponse<String> listApiResponse = new ApiResponse<>();
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        try {
            tagService.save(tag.setPostTime(DateUtil.now()));
            // 新增tag时，让 redis 的 tag 缓存作废
            operations.set("mealpickpro:tags:" + tag.getPostUserId(), "[]", Duration.ofSeconds(1));
            listApiResponse.setCode(SystemStatusCode.SUCCESS.getCode()).setMessage("成功添加新标签").setSuccess(true);
        } catch (Exception e) {
            listApiResponse.setCode(SystemStatusCode.INTERNAL_SERVER_ERROR.getCode()).setMessage("添加新标签失败").setSuccess(false);
        }
        return listApiResponse;
    }

    /**
     * 编辑标签
     *
     * @param tag 编辑的标签信息
     * @return 返回成功与否
     */
    @PutMapping()
    public ApiResponse<String> doModifyTag(@RequestBody Tag tag) {
        ApiResponse<String> listApiResponse = new ApiResponse<>();
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        try {
            tagService.updateById(tag);
            // 新增tag时，让 redis 的 tag 缓存作废
            operations.set("mealpickpro:tags", "[]", Duration.ofSeconds(1));
            listApiResponse.setCode(SystemStatusCode.SUCCESS.getCode()).setMessage("修改标签信息成功").setSuccess(true);
        } catch (Exception e) {
            listApiResponse.setCode(SystemStatusCode.INTERNAL_SERVER_ERROR.getCode()).setMessage("修改标签信息失败").setSuccess(false);
        }
        return listApiResponse;
    }

    /**
     * 根据id删除一个标签
     *
     * @param tagId 要删除的标签id
     * @return 返回删除成功与否
     */
    @DeleteMapping()
    public ApiResponse<String> doRemoveTag(Integer tagId, Integer userId) {
        ApiResponse<String> listApiResponse = new ApiResponse<>();
        if (tagService.removeTagById(tagId, userId)) {
            listApiResponse.setCode(SystemStatusCode.SUCCESS.getCode()).setMessage("成功删除标签！").setSuccess(true);
        } else {
            listApiResponse.setCode(500).setMessage("权限不足，删除食物失败，请联系管理员删除").setSuccess(false);
        }
        return listApiResponse;
    }
}
